// ????
#include <stdio.h>
#include <stdlib.h>
#define N 8
typedef struct point
{
	int x, y;
};

int map[N][N] = {0};
int dir[2][8] = {{0, 1, 1, 1, 0, -1, -1, -1}, {1, 1, 0, -1, -1, -1, 0, 1}};
int isboundary(int x, int y)
{
	if (x == 0 || y == 0 || x == N - 1 || y == N - 1)
	{
		return 1;
	}
	if ((map[x + 1][y] == 0 && map[x - 1][y] == 0) || (map[x][y + 1] == 0 && map[x][y - 1] == 0))
	{
		return -1;
	}
	for (int i = 0; i < 8; i += 2)
	{
		int x1 = x + dir[0][i];
		int y1 = y + dir[1][i];
		if (x1 > 0 && x1 < N && y1 > 0 && y1 < N)
		{
			if (map[x1][y1] == 1)
			{
				return 1;
			}
		}
	}
	return -1;
}

int main()
{
	/*******************code*******************/
	int a[N][N] = {{1, 0, 1, 1, 1, 1, 1, 1},
				   {1, 0, 1, 1, 1, 1, 1, 1},
				   {1, 0, 1, 1, 1, 1, 1, 1},
				   {1, 0, 1, 1, 1, 0, 1, 1},
				   {0, 0, 0, 0, 0, 0, 0, 0},
				   {0, 0, 0, 0, 0, 0, 0, 0},
				   {1, 0, 0, 0, 0, 0, 0, 1},
				   {1, 1, 0, 0, 0, 0, 1, 1}};
	for (int ii = 0; ii < N; ii++)
	{
		for (int jj = 0; jj < N; jj++)
		{
			map[ii][jj] = a[ii][jj];
		}
	}

	point start;
	start.x = 4;
	start.y = 0;
	map[start.x][start.y] = 2;
	int code[100] = {0};
	point stack[100];
	int top = -1;
	int by_code[100];
	int by_top = -1;
	stack[++top] = start;
	while (1)
	{
		point t = stack[top];
		if (by_top >= 0 && (t.x == start.x && t.y == start.y))
		{
			for (int j = 0; j <= by_top; j++)
			{
				printf("%3d", by_code[j]);
			}

			break;
		}
		int flag = 0;
		for (int i = 7; i >= 0; i--)
		{
			point w;
			w.x = t.x + dir[0][i];
			w.y = t.y + dir[1][i];
			if (w.x > 0 && w.x < N - 1 && w.y > 0 && w.y < N - 1)
				if (map[w.x][w.y] == 0 && isboundary(w.x, w.y) == 1)
				{
					map[w.x][w.y] = 2;
					flag = 1;
					stack[++top] = w;
					code[top] = i;
					by_code[++by_top] = i;
					break;
				}
		}
		if (!flag)
		{
			by_code[++by_top] = (code[top--] + 4) % 8;
		}
	}

	/******************************************/
	printf("\n\n****************************\n");
	printf("Press Enter key to continue\n");
	getchar();
	return 0;
	/******************************************/
}
